package com.devops.graphql.scalar;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.netflix.graphql.dgs.DgsScalar;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
import org.jetbrains.annotations.NotNull;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * ClassName JsonObjectScalar
 * Description TODO
 * Author heyabo
 * Date 2022/11/17 11:05
 * Version 1.0
 **/
@DgsScalar(name = "JSON")
public class JsonObjectScalar implements Coercing<JSON, String> {
    @Override
    public String serialize(@NotNull Object dataFetcherResult) throws CoercingSerializeException {
        if (dataFetcherResult instanceof JSON){
            JSON json = (JSON) dataFetcherResult;
            return json.toString();
        }else {
            throw new CoercingSerializeException("Not a valid JSON");
        }
    }

    @Override
    public @NotNull JSON parseValue(@NotNull Object input) throws CoercingParseValueException {
        return JSONUtil.parse(input);
    }

    @Override
    public @NotNull JSON parseLiteral(@NotNull Object input) throws CoercingParseLiteralException {
        if (input instanceof JSON) {
            return JSONUtil.parse(input);
        }

        throw new CoercingParseLiteralException("Value is not a valid ISO JSON");
    }
}
